

//
//  HMComposeViewController.m
//  黑马微博-wzy
//
//  Created by Mac on 2017/2/12.
//  Copyright © 2017年 Mac. All rights reserved.
//

#import "HMComposeViewController.h"
#import "HMAccountTool.h"
#import "HMTextView.h"
#import "HMComposeToolbar.h"
#import "HMComposePhotosView.h"
#import "HMEmotionKeyboard.h"


@interface HMComposeViewController ()<HMComposeToolbarDelete, UITextViewDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate>
//输入框
@property (nonatomic, strong) HMTextView *textView;
//键盘上方工具条
@property (nonatomic, strong) HMComposeToolbar *toolbar;
//发布图片的视图
@property (nonatomic, strong) HMComposePhotosView *photosView;

@property (nonatomic, strong) HMEmotionKeyboard *keyboard;


@end

@implementation HMComposeViewController

//懒加载 创建自定义键盘
- (HMEmotionKeyboard *)keyboard{

    if (!_keyboard) {
        //如果不存在就创建
        _keyboard = [HMEmotionKeyboard keyboard];
        _keyboard.width = kScreenWidth;
        _keyboard.height = 216;
        
    }
    return  _keyboard;
}


- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor whiteColor];
    //1.设置 导航条 内容
    [self setupNavBar];
    
    //2.添加输入控件
    [self setupTextView];
    
    //3.添加工具条
    [self setupToolBar];
    
    //4.添加显示图片的相册控件
    [self setupPhotosView];
    

    
}


- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    //textView 成为第一响应者,目的调出键盘(用户一进到这个界面,键盘就自动弹出)
    [self.textView becomeFirstResponder];
}


#pragma mark - 添加显示图片的相册控件
- (void)setupPhotosView{
    HMComposePhotosView *photosView = [[HMComposePhotosView alloc] init];
    photosView.width = self.textView.width;
    photosView.height = self.textView.height;
    photosView.y = 70;
    [self.textView addSubview:photosView];
    self.photosView = photosView;
}


#pragma mark - 添加工具条
- (void)setupToolBar{

    //1.创建
    HMComposeToolbar *toolbar = [[HMComposeToolbar alloc] init];
    toolbar.width = self.view.width;
    toolbar.height = 44;
    toolbar.delegate = self;
    self.toolbar = toolbar;
    
    //2.显示
    //键盘下去的时候,toolbar在视图的最下面,但并不消失
    toolbar.y = self.view.height - toolbar.height;
    [self.view addSubview:toolbar];
}


#pragma mark - 设置 导航条 内容
- (void)setupNavBar{
    NSString *name = [HMAccountTool account].name;
    if (name) {
        //构建文字
        NSString *prefix = @"发微博";
        NSString *text = [NSString stringWithFormat:@"%@\n%@", prefix, name];
        NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:text];
        [string addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:15] range:[text rangeOfString:prefix]];
        [string addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range:[text rangeOfString:name]];
        
        //创建 label
        UILabel *titleLabel = [[UILabel alloc] init];
        titleLabel.attributedText = string;
        titleLabel.numberOfLines = 0;
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.width = 100;
        titleLabel.height = 44;
        self.navigationItem.titleView = titleLabel;
        
        
    }else{
        self.title = @"发微博";
    }
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancel)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"发送" style:UIBarButtonItemStylePlain target:self action:@selector(send)];
    self.navigationItem.rightBarButtonItem.enabled = NO;

}


//取消
- (void)cancel{
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

//发送
- (void)send{
//    HMLog(@"发送");
    /*
     (1)statuses/update	发布一条微博信息
     url:https://api.weibo.com/2/statuses/update.json
     ①access_token	true	string	采用OAuth授权方式为必填参数，OAuth授权后获得。
     ②status	true	string	要发布的微博文本内容，必须做URLencode，内容不超过140个汉字。
     
     (2)statuses/upload	上传图片并发布一条微博
     url:https://upload.api.weibo.com/2/statuses/upload.json
     ①access_token	false	string	采用OAuth授权方式为必填参数，其他授权方式不需要此参数，OAuth授权后获得。
     ②status	true	string	要发布的微博文本内容，必须做URLencode，内容不超过140个汉字。
     ③pic	true	binary	要上传的图片，仅支持JPEG、GIF、PNG格式，图片大小小于5M。
     */
    
    //1.先判断发布的微博内容是否包含图片
    if (self.photosView.images.count) {
        //包含图片
        [self sendStatusWithImage];
    }else{
        //不包含图片
        [self sendStatusWithoutImage];
    }
    
    //2.关闭发布控制器
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 发布包含图片的微博
- (void)sendStatusWithImage{
    NSString *url = @"https://upload.api.weibo.com/2/statuses/upload.json";
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    //access_token	true	string	采用OAuth授权方式为必填参数，OAuth授权后获得。
    params[@"access_token"] = [HMAccountTool account].access_token;
    params[@"status"] = self.textView.text;
    
    
//    [manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//        //拼接图片参数
//        //目前新浪开放的开发微博的接口,最多只能上传一张图片
//        UIImage *image = [self.photosView.images firstObject];
//        NSData *data = UIImageJPEGRepresentation(image, 1.0);
//        //拼接文件
//        [formData appendPartWithFileData:data name:@"pic" fileName:@"status.jpg" mimeType:@"image/jepg"];
//        
//    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        //成功
//        [MBProgressHUD showSuccess:@"发布成功"];
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        //失败
//        [MBProgressHUD showError:@"发布失败"];
//    }];
    

}


#pragma mark - 发布包不含图片的微博
- (void)sendStatusWithoutImage{
      //1.封装参数
    HMSendStatusParam *param = [[HMSendStatusParam alloc] init];
    param.status = self.textView.text;
    
    [HMStatusTool sendStatusWithParams:param success:^(HMSendStatusResult *result) {
        //成功
        [MBProgressHUD showSuccess:@"发布成功"];
        
    } failure:^(NSError *error) {
        //失败
        [MBProgressHUD showError:@"发布失败"];
    }];
}


#pragma mark - 添加输入控件
- (void)setupTextView{
    //UITextView 继承自 UIScrollView
    
    //1.创建控件
    HMTextView *textView = [[HMTextView alloc] init];
    //竖直方向上拥有弹簧效果,可拖拽(目的是让键盘下去,以便显示出被键盘遮挡的部分)
    textView.alwaysBounceVertical = YES;
    textView.backgroundColor = [UIColor whiteColor];
    textView.frame = self.view.bounds;
    //设置代理(监听textView 的拖拽 => 即监听 UIScrollView 的拖拽 => 实现UIScrollView 的代理方法)
    textView.delegate = self;

    [self.view addSubview:textView];
    
    self.textView = textView;
    //2.设置提醒文字(占位文字)
     textView.placehoder = @"分享新鲜事...";
    
    //3.设置字体
    textView.font = [UIFont systemFontOfSize:15];
    
    //4.监听键盘
    //键盘即将弹出
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    //键盘即将隐藏
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
}

#pragma mark - 去除监听
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - UITextViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    //开始拖拽,键盘下去
    [self.view endEditing:YES];
}

//监听用户是否输入内容,如果有内容:右上角的发送按钮可点击; 如果没有内容,右上角的发送按钮则不可点击
- (void)textViewDidChange:(UITextView *)textView{

    self.navigationItem.rightBarButtonItem.enabled = textView.hasText;
}


#pragma mark - 键盘即将弹出
- (void)keyboardWillShow:(NSNotification *)note{

//    NSLog(@"键盘即将弹出:%@", note);
/*
 键盘即将弹出:NSConcreteNotification 0x60000025b690 {name = UIKeyboardWillShowNotification; userInfo = {
	UIKeyboardFrameBeginUserInfoKey = NSRect: {{0, 568}, {320, 253}},
	UIKeyboardCenterEndUserInfoKey = NSPoint: {160, 441.5},
	UIKeyboardBoundsUserInfoKey = NSRect: {{0, 0}, {320, 253}},
	UIKeyboardFrameEndUserInfoKey = NSRect: {{0, 315}, {320, 253}},
	UIKeyboardAnimationDurationUserInfoKey = 0.25,
	UIKeyboardCenterBeginUserInfoKey = NSPoint: {160, 694.5},
	UIKeyboardAnimationCurveUserInfoKey = 7,
	UIKeyboardIsLocalUserInfoKey = 1
 }}
 */
   //1.键盘弹出需要的时间
    CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    //2.动画
    [UIView animateWithDuration:duration animations:^{
      //获取键盘frame
        CGRect keyboardFrame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
        //获取键盘高度
        CGFloat keyboardH = keyboardFrame.size.height;
        self.toolbar.transform = CGAffineTransformMakeTranslation(0, -keyboardH);
    }];
    
}

#pragma mark - 键盘即将隐藏
- (void)keyboardWillHide:(NSNotification *)note{

//    NSLog(@"键盘即将隐藏:%@", note);
    //1.键盘隐藏需要的时间 可 与键盘显示时需要是时间设置为一样
    CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    //2.动画
    [UIView animateWithDuration:duration animations:^{
        //回复键盘原来位置
        self.toolbar.transform = CGAffineTransformIdentity;
    }];
    
}

#pragma mark - HMComposeToolbarDelegate
//监听 toolbar 内部按钮的点击
- (void)composeTool:(HMComposeToolbar *)toolbar didClickedButton:(HMComposeToolbarButtonType)buttonType{
    switch (buttonType) {
        case HMComposeToolbarButtonTypeCamera://照相机
            [self openCamera];
            break;
        case HMComposeToolbarButtonTypePicture://相册
            [self openAlbum];
            break;
        case HMComposeToolbarButtonTypeEmotion://表情
            [self openEmotion];
            break;
            
        default:
            break;
    }
}

#pragma mark - 打开照相机
/*
 typedef NS_ENUM(NSInteger, UIImagePickerControllerSourceType) {
 UIImagePickerControllerSourceTypePhotoLibrary,   //图片列表
 UIImagePickerControllerSourceTypeCamera,         //摄像头
 UIImagePickerControllerSourceTypeSavedPhotosAlbum//相机相册
 };

 */
- (void)openCamera{
//    HMLog(@"相机");
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) return;
    
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    //摄像头
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    picker.delegate = self;
    [self presentViewController:picker animated:YES completion:nil];
    
}

#pragma mark - 打开相册
- (void)openAlbum{
//    HMLog(@"相册");
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) return;
    
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    //图片列表
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    [self presentViewController:picker animated:YES completion:nil];
    
}

#pragma mark ******** 表情 *****************
- (void)openEmotion{
//    HMLog(@"表情");
    HMLog(@"表情键盘:%@", self.textView.inputView); //表情键盘:(null) -> 说明不是系统键盘,我们可以自定义表情键盘放在上面
    
    if (self.textView.inputView) {
        //当self.textView.inputView != nil的时候,说明是自定义键盘,需设为系统键盘:即把自定义键盘清空
        self.textView.inputView = nil;
        
        //当前是系统键盘时,显示 "表情"图标->意为,点击"表情"图标会调出表情键盘
        self.toolbar.showEmotionButton = YES;
        
    }else{
        //== nil的时候,说明是系统键盘,需设为自定义键盘

        self.textView.inputView = self.keyboard;
    
        //当前是自定义键盘时,显示 "键盘"图标->意为,点击"键盘"图标会调出系统键盘
        self.toolbar.showEmotionButton = NO;

    }
    
    //注意:键盘切换,需在下次启用的时候生效:可先取消第一响应,再注册第一响应即可
    //取消第一响应
    [self.textView resignFirstResponder];
    
    //设置动画
    [UIView animateWithDuration:0.2 animations:^{
        //
        //注册第一响应
        [self.textView becomeFirstResponder];
    }];

}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    //1.取出选中的图片
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    
    //2.添加图片到相册中
    [self.photosView addImage:image];
}

@end
